package com.mengwen.backstage.controller;

import com.mengwen.backstage.pojo.Admin;
import com.mengwen.backstage.service.AdminService;
import com.mengwen.backstage.util.JwtUtil;
import com.mengwen.backstage.util.MD5Util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author LiangYonghui
 * @date 2020/4/7 10:40
 * @description 管理员登录
 */
@Controller
public class AdminLoginController {
    private static final Log LOG = LogFactory.getLog(AdminLoginController.class);


    @Autowired
    private AdminService adminService;

    /**
     * 跳转管理员登录页面
     *
     * @return
     */
    @RequestMapping("/admin/login")
    public String adminToLogin() {
        return "admin_login";
    }

    @RequestMapping("/mengwen/admin/login")
    public String adminLogin(HttpServletResponse response, HttpServletRequest httpServletRequest, Model model) throws IOException, ServletException {
        LOG.info("管理员登录：");
        String accountNumber = httpServletRequest.getParameter("account_number");
        String password = httpServletRequest.getParameter("password");
        String md5Password = MD5Util.md5Encrypt32Upper(password);
        System.out.println(accountNumber);
        System.out.println(md5Password);
        Admin admin = adminService.login(accountNumber, md5Password);
        if (admin != null) {
            LOG.info("管理员：" + admin.getNickname() + "登录成功。openid:" +  admin.getOpenid());
            // 分发jwttoken
            String adminToken = JwtUtil.geneAdminJsonWebToken(admin);
            System.out.println(adminToken);
            model.addAttribute("adminToken",adminToken);

            model.addAttribute("admin",admin);
            return "back_management_page";
        } else {
            // 账号密码不正确：
            model.addAttribute("errorMsg", "账号或密码错误");
            System.out.println("账号或密码错误");
            return "admin_login";
        }


    }

}
